package com.yanqu.road.dao.impl.player;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.player.UserPassword;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserPasswordDaoImpl extends TempDataObjectDao<UserPassword> {

	public UserPassword getUserPassword(long userId) {
		ResultSet rs = null;
		CallableStatement call = null;
		String sql = "select * from t_u_password where userId=?";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareCall(sql);
			call.setLong(1, userId);
			rs = call.executeQuery();
			while (rs.next()) {
				UserPassword data = parse(rs);
				return data;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			getDb().closeConnection(call, rs);
		}
		return null;
	}

	@Override
	protected boolean addData(UserPassword data) {
		PreparedStatement call = null;
		String sql = "INSERT INTO t_u_password(userId,recyclePassword,lockRecycleEndTime) VALUES(?,?,?)";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setLong(i++, data.getUserId());
			call.setString(i++, data.getRecyclePassword());
			call.setLong(i++, data.getLockRecycleEndTime());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected boolean updateData(UserPassword data) {
		PreparedStatement call = null;
		String sql = "UPDATE t_u_password SET recyclePassword=?,lockRecycleEndTime=? WHERE userId=?";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setString(i++, data.getRecyclePassword());
			call.setLong(i++, data.getLockRecycleEndTime());

			call.setLong(i++, data.getUserId());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected UserPassword parseData(ResultSet rs) throws SQLException {
		UserPassword data = new UserPassword();
		data.setUserId(rs.getLong("userId"));
		data.setRecyclePassword(rs.getString("recyclePassword"));
		data.setLockRecycleEndTime(rs.getLong("lockRecycleEndTime"));
		return data;
	}
}
